import { Component, OnInit, ViewChild } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { SFSchema, SFComponent } from '@delon/form';
import { NzMessageService } from 'ng-zorro-antd/message';
import { environment } from '@env/environment';
import { NzTreeComponent, NzTreeNode } from 'ng-zorro-antd/tree';
import { SysKeyValueService } from '@api/sys/service/sysKeyValue.service';

@Component({
  selector: 'app-sys-keyValue',
  templateUrl: './keyValue.component.html',
})
export class SysKeyValueComponent implements OnInit {
  constructor(private http: _HttpClient, private msgSrv: NzMessageService, private sysKeyValueService: SysKeyValueService) {}
  keyword: string = '';
  url = `${environment.sys.ctx}/sysKeyValue/findByQueryParams`;

  selectResource: any = {};

  @ViewChild('sf', { static: false }) sf!: SFComponent;
  searchSchema: SFSchema = {
    properties: {
      name: {
        type: 'string',
        title: '名称',
      },
    },
  };

  @ViewChild('rootResourcesTree', { static: false }) rootResourcesTree!: NzTreeComponent;

  rootResources = [{ title: '键值树', key: '0', isExpanded: true, children: [] }];

  menu: any = { '0': { id: '0', code: '' } };

  ngOnInit() {
    this.treeExpandChange(this.rootResourcesTree.getTreeNodes()[0]);
  }

  delete(record: any) {
    this.http.post(`${environment.sys.ctx}/sysKeyValue/deleteById/${record.key}`).subscribe((res) => {
      this.msgSrv.success(`成功删除`);
    });
  }

  add(node: any) {
    const parentkeyPath = this.menu[node.key].keyPath ? this.menu[node.key].keyPath : '';
    this.selectResource = { parentId: node.key, keyPath: `${parentkeyPath}/` };
  }

  treeExpandChange(node: NzTreeNode, isSync: boolean = false): void {
    if ((node && node.getChildren().length === 0 && node.isExpanded) || isSync) {
      node.isLoading = true;
      const children: any[] = [];
      this.http.get(`${environment.sys.ctx}/sysKeyValue/findByParentId/${node.key}`).subscribe((res) => {
        if (res.length > 0) {
          res.forEach((element: any) => {
            this.menu[element.id] = element;
            children.push({ title: element.value, key: element.id });
          });
          node.clearChildren();
          node.addChildren(children);
          // tslint:disable-next-line: deprecation
          node.setExpanded(true);
        } else {
          node.isLeaf = true;
        }
        node.isLoading = false;
      });
    }
  }

  edit(node: NzTreeNode): void {
    if (node.key === '0') {
      this.add(node);
      return;
    }
    this.sysKeyValueService.findById(node.key).subscribe((res) => {
      this.selectResource = res;
    });
  }
}
